package com.bird.thread.base.thread;

/**
 * @author sijunqiang
 * @data 2021/7/1 22:44
 * @description: 两个线程交替打印0~100的奇偶数，用wait和notify
 */
public class WaitNotifyPrintOddEveWait {

    private static Object lock = new Object();

    private static int count = 0;


    public static void main(String[] args) {
        new Thread(new TurningRunner(),"偶数线程").start();
        new Thread(new TurningRunner(),"奇数线程").start();
    }

    // 内部类-
    //1:拿到锁,就打印
    // 2: 打印完 唤醒其它线程 自己进入休眠
    static class TurningRunner implements Runnable {
        @Override
        public void run() {
            while (count <= 100) {
                synchronized (lock) {
                    System.out.println(Thread.currentThread().getName() + " : " + count++);
                    //唤醒和这把锁相关的被阻塞的线程 重新进入 runnable状态 准备争取锁资源
                    lock.notify();
                    if (count <= 100) {
                        try {
                            lock.wait();// 释放这个对象锁的拥有权 并进入阻塞期。
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}
